<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    width="900px">
    <el-form
      :model="form"
      :rules="rule"
      ref="form"
      style="width: 820px"
      label-width="100px"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="form.category_id" placeholder="请选择">
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="content">
        <wang-editor v-model="form.content"></wang-editor>
      </el-form-item>
    </el-form>
    <div slot="footer" style="display: flex;justify-content: center;">
      <el-button type="primary"
                 @click="cancel">取消
      </el-button>
      <el-button type="primary"
                 @click="submit">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { store, edit } from '../api'

export default {
  name: 'view-dialog',
  data () {
    return {
      dialogVisible: false,
      id: undefined,
      form: {
        title: '',
        category_id: '',
        content: ''
      },
      rule: {
        title: [
          { required: true, message: '请输入标题' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters('setting/help/cate', ['list']),
    title () {
      return this.id === undefined ? '新增' : '编辑'
    }
  },
  methods: {
    ...mapActions('setting/help/cate', ['fetchList']),
    handleClose (done) {
      done()
    },
    open (row = false) {
      this.dialogVisible = true
      this.fetchList({ limit: 100, page: 1 })
      if (row === false) {
        this.id = undefined
        this.form = {
          title: '',
          category_id: '',
          content: ''
        }
      } else {
        const { id, title, category_id, content } = row
        Object.assign(this.form, { title, category_id, content })
        this.id = id
      }
      return new Promise((resolve) => {
        this._resolve = resolve
      })
    },
    async submit () {
      await this.$refs.form.validate()
      if (this.id) {
        await edit(this.id, this.form)
      } else {
        await store(this.form)
      }
      this.$message.success('更新成功')
      this.cancel()
    },
    cancel () {
      this.close()
    },
    close () {
      this.dialogVisible = false
      this._resolve({ refresh: true })
    }
  }
}
</script>

<style scoped>

</style>
